<template>
  <div class="tinymce-editor"><editor v-model="myValue" :init="init" :disabled="disabled" @onClick="onClick"></editor></div>
</template>
<script>
import { Notification } from 'element-ui';

import { getToken } from '@/utils/auth';
import { uploadFile } from '@/api';

import tinymce from 'tinymce/tinymce';
import Editor from '@tinymce/tinymce-vue';
// import VueTinymce from '@packy-tang/vue-tinymce';

// 编辑器插件plugins
// 更多插件参考：https://www.tiny.cloud/docs/plugins/
import 'tinymce/themes/silver';
import 'tinymce/plugins/paste'; // 插入上传图片插件
// import "tinymce/plugins/powerpaste"; // 插入加强图片贴入插件
import 'tinymce/plugins/image'; // 插入上传图片插件
import 'tinymce/plugins/media'; // 插入视频插件
import 'tinymce/plugins/table'; // 插入表格插件
import 'tinymce/plugins/lists'; // 列表插件
import 'tinymce/plugins/wordcount'; // 字数统计插件
import 'tinymce/icons/default'
// import "tinymce/plugins/lineheight"; // 行高插件

export default {
  components: {
    Editor
  },
  props: {
    /** 宽度 */
    width: {
      type: [Number, String],
      default: 1080
    },
    /** 高度 */
    height: {
      type: [Number, String],
      default: 466
    },
    /** 默认内容 */
    value: {
      type: String,
      default: ''
    },
    /** 是否禁用 */
    disabled: {
      type: Boolean,
      default: false
    },
    /** 字体样式选择 */
    fontFormats: {
      type: String,
      default:
        '微软雅黑=Microsoft YaHei,Helvetica Neue,PingFang SC,sans-serif;苹果苹方=PingFang SC,Microsoft YaHei,sans-serif;宋体=simsun,serif;Andale Mono=andale mono,times;Arial=arial,helvetica,sans-serif;Arial Black=arial black,avant garde;Book Antiqua=book antiqua,palatino;Comic Sans MS=comic sans ms,sans-serif;Courier New=courier new,courier;Georgia=georgia,palatino;Helvetica=helvetica;Impact=impact,chicago;Symbol=symbol;Tahoma=tahoma,arial,helvetica,sans-serif;Terminal=terminal,monaco;Times New Roman=times new roman,times;Trebuchet MS=trebuchet ms,geneva;Verdana=verdana,geneva;Webdings=webdings;Wingdings=wingdings,zapf dingbats'
    },
    /** 字体大小设置 */
    fontsizeFormats: {
      type: String,
      default: '11px 12px 14px 16px 18px 20px 22px 24px 26px 28px 30px 32px 34px 36px 48px' // 字体大小选择器设置
    },
    /** 插件选择 */
    plugins: {
      type: [String, Array],
      // default: "lists image media table wordcount lineheight paste",
      default:
        'print paste preview searchreplace autolink fullscreen image link media code codesample table charmap hr pagebreak nonbreaking anchor advlist lists textpattern help emoticons autosave wordcount'
    },
    /** 工具栏显示插件选择 */
    toolbar: {
      type: [String, Array],
      // default:
      //   " styleselect | undo redo | bold italic forecolor backcolor lineheight indent2em  | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | lists image table | removeformat",
      default:
        'formatselect fontselect fontsizeselect | lineheight | alignleft aligncenter alignright alignjustify | forecolor backcolor bold italic underline strikethrough link | cut copy | code undo redo restoredraft | bullist numlist blockquote subscript superscript removeformat | table image media charmap emoticons hr pagebreak print preview | fullscreen wordcount'
    }
  },
  data() {
    return {
      init: {
        branding: false,
        language_url: '/tinymce/langs/zh_CN.js', //public目录下
        language: 'zh_CN',
        skin_url: '/tinymce/skins/ui/oxide', //public目录下
        height: this.height,
        width: this.width,
        plugins: this.plugins, // 父组件传入 或者 填写个默认的插件 要选用什么插件都可以 去官网可以查到
        toolbar: this.toolbar, // 工具栏 我用到的也就是lists image media table wordcount 这些 根据需求而定
        font_formats: this.fontFormats,
        fontsize_formats: this.fontsizeFormats,
        images_upload_url: '', //上传路径
        // 此处为图片上传处理函数，这个直接用了base64的图片形式上传图片，
        // 如需ajax上传可参考https://www.tiny.cloud/docs/configure/file-image-upload/#images_upload_handler

        // 解决粘贴图片后，不自动上传，而是使用base64编码。
        /** powerpaste功能 付费插件 */
        // powerpaste_allow_local_images: false, // 是否允许带图片复制

        // urlconverter_callback: (url, node, onSave, name) => {
        //   if (node === "img" && url.startsWith("blob:")) {
        //     // Do some custom URL conversion
        //     // console.log('urlConverter:', url, node, onSave, name)
        //     tinymce.activeEditor && tinymce.activeEditor.uploadImages();
        //   }
        //   // Return new URL
        //   return url;
        // },
        image_dimensions: false,
        paste_data_images: false,

        paste_preprocess: function(plugin, args) {
          let temp = args.content.replace(/<p><img\s?src="data.*?<\/p>/g, '');
          args.content = temp;

          Notification({
            title: '错误',
            message: '禁止粘贴图片,只允许上传图片',
            type: 'warning'
          });
        },

        // 官网抄的图片上传 项目如果用了vue-resource可以用$http 因为比较懒就没改
        images_upload_handler: (blobInfo, success, failure) => {
          // console.log(blobInfo, success, failure);
          // console.log(blobInfo.filename(), blobInfo.blob());
          var formData;
          var file = blobInfo.blob();
          formData = new FormData();
          formData.append('file', file, file.name);
          // var headers = {
          //   Authorization: "Bearer " + getToken(),
          //   // Authorization: "",
          // };
          uploadFile(formData).then(res => {
            if (res.code === 403) {
              failure('HTTP Error: ' + res.code, { remove: true });
              return;
            }
            if (res.code < 200 || res.code >= 300) {
              failure('HTTP Error: ' + res.code);
              return;
            }

            success(res.data);
          });
        }
      },
      myValue: this.value
    };
  },
  mounted() {
    tinymce.init({});
  },
  methods: {
    onClick(e) {
      this.$emit('onClick', e, tinymce);
    }
  },
  watch: {
    value(newValue) {
      this.myValue = newValue;
    },
    myValue(newValue) {
      this.$emit('input', newValue);
    }
  }
};
</script>
